package ntd.util.frame.websocket;

import cn.hutool.log.StaticLog;
import lj.netty.websocket.SocketUtils;
import lj.netty.websocket.WebSocketHandler;
import lj.netty.websocket.WebSocketService;
import lj.netty.websocket.bo.WebSocketMsgBo;
import ntd.util.frame.auth.ToolLogin;
import ntd.util.frame.ssh.ToolWebJsch;

/**
 * 命令行websocket
 */
public class WebSocketWithCmd {

    
    public static void init() {
        ToolWebJsch toolWebJsch = new ToolWebJsch();

        WebSocketService webSocketService = new WebSocketService(33610, new WebSocketHandler() {
            @Override
            public void initChannel(WebSocketMsgBo webSocketMsgBo) {
                String userId = ToolLogin.getUserId(webSocketMsgBo.getParamMap().get("token"));
                // 绑定用户id和websocket通道
                SocketUtils.bindChannel(webSocketMsgBo.getChannelId().asShortText(), webSocketMsgBo.getChannelId());
                // 初始化webssh连接
                toolWebJsch.initConnection(webSocketMsgBo.getChannelId().asShortText());
            }

            @Override
            public String onMsg(WebSocketMsgBo webSocketMsgBo) {
                StaticLog.info(webSocketMsgBo.getMsg());
                toolWebJsch.recvHandle(webSocketMsgBo.getChannelId().asShortText(), webSocketMsgBo.getMsg());
                return "";
            }

            @Override
            public void onClose(WebSocketMsgBo webSocketMsgBo) {
                toolWebJsch.close(webSocketMsgBo.getChannelId().asShortText());
            }
        });

        try {
            webSocketService.start();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        init();
    }
}
